<?php


namespace App\Http\Rest\Admin\Resource;

use Framework\Foundation\Database\FDB;
use Framework\Foundation\Response\ResponseGen;

class MenuTree
{
    public function getList()
    {
        $query = FDB::from('menu')->where(['status > ?' => -1]);
        $list = $query->fetchAll();
        $treeData = $this->tree($list);

        $ret = $this->treeToSelect($treeData);


        return ResponseGen::success($ret);
//        return $ret;
    }

    public function tree($arr, $pid = 0, $level = 0)
    {
        if ($level == 10) {
            return [];
        }
        $res = array();
        foreach ($arr as $v) {
            if ($v['pid'] == $pid) {
                //说明找到，先保存，然后在递归查找
                $v['level'] = $level;

                $child = $this->tree($arr, $v['menu_id'], $level + 1);
                if (!empty($child)) {
                    $v['_child'] = $child;
                }
                $res[] = $v;
            }
        }
        return $res;
    }


    private function treeToSelect($list, $level = 0, $title = 'title')
    {
        static $formatTree = [];
        foreach ($list as $key => $val) {
            $tmp_str = str_repeat("&nbsp;", $level * 2);
            $tmp_str .= "└";
            $val['level'] = $level;
            $val['title_show'] = $level == 0 ? $val[$title] . "&nbsp;" : $tmp_str . $val[$title] . "&nbsp;";
            // $val['title_show'] = $val['id'].'|'.$level.'级|'.$val['title_show'];
            if (!array_key_exists('_child', $val)) {
                array_push($formatTree, $val);
            } else {
                $tmp_ary = $val['_child'];
                unset($val['_child']);
                array_push($formatTree, $val);
                $this->treeToSelect($tmp_ary, $level + 1, $title); //进行下一层递归
            }
        }
        return $formatTree;
    }
}
